//
//  BHPersonalUserInfoViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/30.
//

import UIKit

class BHPersonalUserInfoViewController: BHBaseViewController {
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.regiseterNib(nibName: "BHPeronalUserHeaderEditeCell")
        view.regiseterNib(nibName: "BHComInputTextCell")
        view.regiseterNib(nibName: "BHComArrowChoseCell")
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    let height: CGFloat = (20+44+UIScreen.safeBottomHeight+10)
    
    lazy var bottomView: UIView = {
        let view = UIView.init(frame: CGRect(x: 0, y: UIScreen.height-self.height, width: UIScreen.width, height: self.height))
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 16, y: 10, width: UIScreen.width-32, height: 44)
        btn.backgroundColor = .color_34CE98
        btn.setTitle("保存", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.addTarget(self, action: #selector(saveInfoEditeAct), for: .touchUpInside)
        btn.addLayerCorner(22, 0, .white)
        view.addSubview(btn)
        view.isHidden = true
        return view
    }()
    
    fileprivate let rowArray: [String] = ["昵称","性别","所在单位","职业"]
    
    var tempModel = BHUserPageDataModel.init()
    
    fileprivate var infoEditing: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.tempModel.loadFromGloab()
        
        self.bh_navigationBar.title_label.text = "详情"
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomView)
        
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.rightBtn.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium)
        self.bh_navigationBar.rightBtn.setTitleColor(.color_999999, for: .normal)
        self.bh_navigationBar.rightBtn.setTitle("编辑", for: .normal)

    }
    
    override func rightBtnAction() {
        self.infoEditing = true
        self.bh_navigationBar.rightBtn.isHidden = true
        self.tableView.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-self.height)
        self.bottomView.isHidden = false
        self.tableView.reloadData()
    }


    @objc func saveInfoEditeAct() {
        self.changeUserInfoService()
    }
}

// 拍照
extension BHPersonalUserInfoViewController {
    func takePic()  {
        BHCommonTool.showPicAlert(showVC: self) { (index) in
            if index == 0 { // 拍照
                BHCommonTool.init().takePhoto { (img) in
                    if img != nil {
                        self.uploadHeader(image: img!)
                    }
                }
            }else { // 相册
                BHCommonTool.init().photeChose(maxCount: 1) { (image, asset) in
                    if image != nil {
                        self.uploadHeader(image: image!)
                    }
                }
            }
        }
    }
}
extension BHPersonalUserInfoViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return self.rowArray.count
        }
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 135
        }
       return 50
    }
    
}

extension BHPersonalUserInfoViewController: UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHPeronalUserHeaderEditeCell", for: indexPath) as! BHPeronalUserHeaderEditeCell
            cell.headerIconBtn.sd_setBackgroundImage(with: URL.init(string: self.tempModel.avatar), for: .normal, completed: nil)
            
            cell.takePicBtn.isHidden = !self.infoEditing
            
            cell.takePicBtn.addBtnAction(action: {[weak self] (_) in
                self?.takePic()
            }, for: .touchUpInside)
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHComInputTextCell", for: indexPath) as! BHComInputTextCell
            let text = self.rowArray[indexPath.row]
            
            cell.name_label.text = text
            cell.text_filed.textColor = .color_999999
            if indexPath.row == 0 { // 昵称
                cell.text_filed.text = self.tempModel.name
                cell.canTextCanEdite = true
            }else if indexPath.row == 1 { //性别
                cell.text_filed.text = self.tempModel.sexName
                cell.canTextCanEdite = false
            }else if indexPath.row == 2 { // 公司
                cell.text_filed.text = self.tempModel.companyName
                cell.canTextCanEdite = true
            }else { // 职业
                cell.text_filed.text = self.tempModel.occupation
                cell.canTextCanEdite = true
            }
            cell.text_filed.isEnabled = self.infoEditing
            cell.textFiledBegainEditingBlock = { [weak self] in
                if indexPath.row != 1 {
                    return
                }
                BHCommonTool.showSheetWith(showVC: self, title: "请选择性别", messages: ["男","女"]) { (index) in
                    if index != -1 {
                        self?.tempModel.sex = index+1
                        tableView.reloadData()
                    }
                }
            }
            
            cell.textFiledDidEndEditingBlock = { [weak self] text in
                if indexPath.row == 0 { // 昵称
                     self?.tempModel.name = text
                   
                }
                if indexPath.row == 2 { // 公司
                    self?.tempModel.companyName = text

                }
                if indexPath.row == 3 { // 职业
                    self?.tempModel.occupation = text
                }
            }
            cell.text_filed.placeholder = "请填写\(text)"
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.view.endEditing(true)
        if indexPath.section == 1 && indexPath.row == 1 {
            if self.infoEditing == false {
                return
            }
            BHCommonTool.showSheetWith(showVC: self, title: "请选择性别", messages: ["男","女"]) { (index) in
                if index != -1 {
                    self.tempModel.sex = index+1
                    tableView.reloadData()
                }
            }
        }
    }
}


extension BHPersonalUserInfoViewController{
    func uploadHeader(image: UIImage) {
        SVProgressHUD.show()

        let manager = BHHTTPClient.init()
        manager.upload(images: [image], progressHandler: nil) { (success, errorMsg, url) in
            SVProgressHUD.dismiss()
            if success == true {
                self.tempModel.avatar = url.first ?? ""
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func changeUserInfoService()  {
        SVProgressHUD.show()
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.put(url: String.me_userInfo_edite_url, paramters: dic) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                self.infoEditing = false
                self.bh_navigationBar.rightBtn.isHidden = false
                self.tableView.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
                self.bottomView.isHidden = true

                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["userId"] = ""
        dic["name"] = self.tempModel.name
        dic["sex"] = self.tempModel.sex
        dic["avatar"] = self.tempModel.avatar
        dic["companyName"] = self.tempModel.companyName
        dic["occupation"] = self.tempModel.occupation
        return dic
    }
}
